<template>
  <!-- :max-height="option.height || '100%'" -->
  <vbt-table
    ref="ElTable"
    :data="data"
    :size="size"
    :border="option.border"
    :stripe="vaildData(option.stripe, true)"
    :height="option.height || '100%'"
    :max-height="option.height || '100%'"
    :show-summary="vaildData(option.showSummary, false)"
    highlight-current-row
    highlight-hover-row
    :row-class-name="tableRowClassName"
    @setCurrentRow="setCurrentRow"
    @selection-change="selectionChange"
    @row-click="rowClick"
    @cell-click="cellClick"
    @row-dblclick="rowDblClick"
    :show-header="option.showHeader"
    :cell-style="cellStyle"
    :header-cell-style="headerCellStyle"
    :isBigData="vaildData(option.isBigData, true)"
    :isTreeTable="vaildData(option.isTreeTable, true)"
    :lazy="option.lazy"
    :load="treeLoad"
    :row-key="option.rowKey"
    :tree-props="option.treeProps"
    :scrollYRenderConfig="option.scrollYRenderConfig"
    v-bind="$attrs"
    v-on="$listeners"
    :key="itemkey"
    class="OceBigTable"
    :initParentFunc="initParentFunc"
    :formateChildFunc="formateChildFunc"
    @expand-change="expandChange"
    @mousewheel="mousewheel"
  >
    <!-- 无数据 -->
    <template slot="empty">
      <div class="noData">
        <img src="../../../../assets/img/zwnr.png" alt />
        <div class="label">{{ '暂无内容' }}</div>
      </div>
    </template>

    <!-- 选择框 -->
    <vbt-table-column
      v-if="option.selection"
      type="selection"
      width="55"
      :align="option.align || 'center'"
      :header-align="option.headerAlign || 'center'"
    ></vbt-table-column>

    <!-- 序号 -->
    <vbt-table-column
      v-if="option.index"
      width="55"
      :align="option.align || 'center'"
      :header-align="option.headerAlign || 'center'"
      label="序号"
    >
      <template slot-scope="scope">
        <!-- <span>{{ scope.$index + 1 }}</span>  返回序号ndex值 启用连续分页-->
        <span>{{ getIndex(scope, 1) }}</span>
      </template>
    </vbt-table-column>

    <!-- 内容 -->
    <template v-for="(item, index) in column">
      <vbt-table-column
        :key="index + item.prop"
        :label="item.label"
        :prop="item.prop"
        :min-width="item.minWidth"
        :sortable="item.sortable"
        :fixed="item.fixed"
        :align="item.align || option.align || 'center'"
        :header-align="item.align || option.headerAlign || 'center'"
        :show-overflow-tooltip="true"
        :formatter="item.formatter"
        v-if="!vaildData(item.hide, false) && vaildData(item.showColumn, true)"
      >
        <!-- 自定义插槽 -->
        <span slot-scope="scope">
          <!--
            @slot 自定义列插槽,插槽名称为对应列的prop。
            @binding {String} name - 插槽名称
            @binding {Object} row - 该条数据对象
          -->
          <slot v-if="item.slot" :name="item.prop" :row="scope.row"></slot>
          <span v-else>{{ handleDetail(scope.row, item) }}</span>
        </span>
      </vbt-table-column>
    </template>

    <!-- 操作栏 -->
    <vbt-table-column
      label="操作"
      align="center"
      :width="option.menuWidth || 200"
      :fixed="option.menuFixed"
      v-if="vaildData(option.menu, true)"
    >
      <template slot-scope="scope">
        <!-- 
          @slot 操作列自定义按钮左
          @binding {Object} row - 该条数据对象
          @binding {Number} index - 该条数据对象下标
           
          删除 修改按钮的 显示/隐藏 传false/true,
         -->
        <slot
          name="menuLeft"
          :row="scope.row"
          :index="getIndex(scope, 0)"
        ></slot>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleUpdate(scope.row)"
          v-if="vaildData(option.editBtn, true)"
          >修改</el-button
        >
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          @click="handleDelete(scope.row)"
          v-if="vaildData(option.delBtn, true)"
          >删除</el-button
        >
        <!-- 
          @slot 操作列自定义按钮右
          @binding {Object} row - 该条数据对象
          @binding {Number} index - 该条数据对象下标
         -->
        <slot
          name="menuRight"
          :row="scope.row"
          :index="getIndex(scope, 0)"
        ></slot>
      </template>
    </vbt-table-column>
  </vbt-table>
</template>

<script>
import vbtTable from './bigTreeTable/table.vue'
import vbtTableColumn from './bigTreeTable/table-column'

let i = 0

/**
 * 对element-ui表格组件进行二次封装，通过JSON格式的配置实现表单
 */
export default {
  name: 'OceBigTable',
  components: { vbtTable, vbtTableColumn },
  data() {
    return {
      size: 'mini',
      cellStyle: {
        height: '',
        padding: '3px 0',
      },

      headerCellStyle: {
        background: '#FAFAFA',
        color: '#000000D9',
        fontSize: '14px !important',
        fontFamily:
          'Chinese Quote,-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;',
      },
      itemkey: Math.random() + '-' + i++,
      expandRowKeys: [],
      getRowKeys(row) {
        // return row[this.option.rowKey];
        return row.billId
      },
      expandMap: new Map(),
    }
  },
  props: {
    /**
     * 表格数据
     */
    data: {
      type: Array,
    },
    /**
     * 组件配置属性，详情见下面Option属性
     */
    option: {
      type: Object,
    },
    /**
     * 列配置，详情见下面Column属性
     */
    column: {
      type: Array,
    },
    //当前分页对象 包含 页码数和分页数
    page: {
      type: Object,
      default: function () {
        return {
          pageSize: 10,
          currentPage: 1,
        }
      },
    },
    continuousIndex: {
      type: Boolean,
      default: false,
    },
    // //设置行样式
    tableRowClassName: {
      type: Function,
      default: function () {
        return 'normal-row'
      },
    },
  },
  watch: {
    data: {
      handler(val) {
        this.clearExpanded()
      },
    },
  },
  mounted() {},
  methods: {
    // 收起所有展开行
    clearExpanded() {
      if (this.expandMap.size < 1) return
      this.expandMap.forEach((val, key) => {
        this.$refs?.ElTable?.toggleRowExpansion(val, false)
        let item = this.$refs?.ElTable?.store?.states?.treeData[key]
        // console.log(item)
        if (item) item.loaded = false
        this.expandMap.delete(key)
      })
    },
    // 滚轮事件
    mousewheel(e) {
      // if (e.deltaY < 0 && zoom < this.maxZoom) {
      //   // 放大
      //   this.$ocean.debounce(this.myMap.zoomIn, 100);
      // } else if (e.deltaY > 0 && zoom > this.minZoom) {
      //   this.$ocean.debounce(this.myMap.zoomOut, 100);
      // }

      // this.$refs.ElTable.doLayout()

      // this.$ocean.debounce(this.$refs.ElTable.doLayout(),500,false)

      this.$ocean.debounce(
        () => {
          // console.log(this.$refs.ElTable.$refs.bodyWrapper.$el.scrollLeft);
          this.$refs.ElTable.$refs.bodyWrapper.$el.scrollLeft++
          this.$refs.ElTable.$refs.bodyWrapper.$el.scrollLeft--
        },
        200,
        false
      )
    },
    // 展开行
    expandChange(row, expanded) {
      // console.log('expandChange', row, expanded);
      // if (!expanded && this.expandMap.has(row[this.option.rowKey])) {
      //   this.expandMap.delete(row[this.option.rowKey])
      // } else
      if (expanded && !this.expandMap.has(row[this.option.rowKey])) {
        this.expandMap.set(row[this.option.rowKey], row)
      }
      this.$nextTick(() => {
        this.$refs.ElTable.doLayout()
      })
    },
    initParentFunc(row, treeData) {
      // console.log('initParentFunc', row, treeData);
    },
    formateChildFunc(row, parentRow, treeData) {
      // console.log('formateChildFunc',row,parentRow,treeData);
    },
    // 树懒加载
    treeLoad(tree, resolve) {
      this.$emit('tree-load', tree, (data) => {
        tree.children = data
        resolve(data)
      })
    },
    // 验证是否存在true/false
    vaildData(val, dafult) {
      return this.$ocean.vaildData(val, dafult)
    },
    refresh() {
      this.itemkey = Math.random()
    },
    // 修改
    handleUpdate(row) {
      /**
       * 修改数据
       * @property {Object} row - 对应数据对象
       */
      this.$emit('handleUpdate', row)
    },
    // 删除
    handleDelete(row) {
      /**
       * 删除数据
       * @property {Object} row - 对应数据对象
       */
      this.$emit('handleDelete', row)
    },
    rowClick(row) {
      /**
       * 点击行
       * @property {Object} row - 对应数据对象
       */
      // this.$emit("handleRowClick", row);
    },
    cellClick(row, value) {
      /**
       * 点击单元格
       * @property {Object} value - 对应数据对象
       */
      // this.$emit("handleCellClick", { row, value });
    },
    /**
     * 行双击
     * @property {Object} row - 对应数据对象
     */
    rowDblClick(row) {
      // this.$emit("HandleRowDblClick", row);
    },
    //设置滚动到当前
    setCurrentRow(row) {
      // this.$emit("setCurrentRow", row);
    },
    // 全选
    toggleAllSelection() {
      this.$refs.ElTable.toggleAllSelection()
    },
    // 选项发送变化
    selectionChange(val) {
      /**
       * 多选项发送变化
       * @property {Array} val - 变化后选中内容列表
       */
      // this.$emit("selection-change", val);
    },
    // 表格内容处理
    handleDetail(row, column) {
      if (['radio', 'select'].includes(column.type)) {
        // console.log(row[column.prop],column.dicData,this.findByValue(row[column.prop],column.dicData))
        return this.findByValue(row[column.prop], column.dicData, column.props)
      } else {
        return row[column.prop]
      }
    },
    // 根据字典的value显示label
    findByValue(value, dic, props) {
      if (!dic || dic.length < 1) return ''
      let valueKey = props ? props.value || 'value' : 'value'
      let labelKey = props ? props.label || 'label' : 'label'
      if (dic.length > 599) console.log(valueKey, labelKey)
      let val = dic.filter((item) => item[valueKey] == value)[0]
      // console.log(val,value)
      if (val == 0) return val[labelKey]

      return val ? val[labelKey] : ''
    },

    //返回表格行序号
    getIndex(scope, type) {
      if (this.continuousIndex) {
        return (
          (this.page.currentPage - 1) * this.page.pageSize + scope.$index + type
        )
      } else {
        return scope.$index + type
      }
    },

    // 为了解决 keep-alive 页面跳转后 scrollTop -> 0 时无法渲染数据
    refreshViewport() {
      this.$refs.ElTable.$refs.bodyWrapper.$el.scrollLeft++
      this.$refs.ElTable.$refs.bodyWrapper.$el.scrollLeft--
    },
  },
}
</script>

<style lang="scss" scoped>
.OceBigTable {
  width: calc(100% - 8px);
  margin: 4px;
  flex-grow: 1;
  height: 100% !important;
  max-height: 100% !important;
}
::v-deep .el-table__empty-block {
  overflow: auto;
}
.noData {
  img {
    // height: 70%;
    width: 40%;
  }
  .label {
    font-size: 30px;
    transform: translate(0, -40px);
  }
}
</style>
